import { ConfigProvider, Select } from 'antd';
import classNames from 'classnames';
import { FC } from 'react';

import { VariableValueField } from '@/components/base/ValueOfType';
import { useDictStore } from '@/store/dict';

import { OperatorSelector } from '../DictSelector/operator';
import { Expression } from '../Expression';
import { LogicExpression } from '../Rules';

export interface ValueSelectorProps {
  className?: string;
  value?: LogicExpression;
  onChange?: (value: ValueSelectorProps['value']) => void;
  leftVariables?: VariableItem[];
  rightVariables?: VariableItem[];
  fieldSize?: 'small' | 'middle' | 'large';
  /** 模式 assignment（赋值），condition（条件） */
  fieldMode?: 'assignment' | 'condition';
}

export enum VarType {
  Boolean = 'BOOLEAN',
  DateTime = 'DATE_TIME',
  Decimal = 'DECIMAL',
  Integer = 'INTEGER',
  List = 'LIST',
  Object = 'OBJECT',
  String = 'STRING',
  Date = 'DATE',
  Enum = 'ENUM'
}

export const ValueSelector: FC<ValueSelectorProps> = memo((props) => {
  const { dictCalcTypeOptions } = useDictStore();
  const { rightType, rightFieldType } = props.value || ({} as LogicExpression);

  const variable2Options = useCallback((variables: VariableItem[]) => {
    return variables.map((item) => {
      return {
        label: item.varLabel,
        value: item.varName,
        varType: item.varType!
      };
    });
  }, []);

  const updateValue = (result: Partial<LogicExpression>) => {
    props.onChange?.({ ...(props.value! || {}), ...result });
  };

  const isConstantType = (rightFieldType: string) => {
    return ['ENUM', 'DATE', 'DATETIME'].includes(rightFieldType?.toUpperCase());
  };

  const leftOptions = useMemo(() => {
    return variable2Options(props.leftVariables!);
  }, [props.leftVariables, variable2Options]);

  const rightOptions = useMemo(() => {
    return variable2Options(props.rightVariables!);
  }, [props.rightVariables, variable2Options]);

  const calcTypeOptions = useMemo(() => {
    if (isConstantType(rightFieldType!)) {
      return dictCalcTypeOptions.filter((item) => item.value === 'CONSTANT');
    }
    return dictCalcTypeOptions;
  }, [dictCalcTypeOptions, rightFieldType]);

  const isTargetValueSelectMultiple = ['IN', 'NOT_IN', 'LIKE', 'NOT_LIKE'].includes(props.value?.operator!);

  const renderRightContent = () => {
    const target = props.leftVariables?.find((item) => item.varName === props.value?.left);
    
    const constantInput = (
      <VariableValueField
        varType={target?.varType}
        options={target?.options || []}
        className="flex-1"
        value={props.value?.right}
        onChange={(right) => {
          updateValue({ right });
        }}
      />
    );

    if (!rightType) {
      return constantInput;
    } else if (rightType === 'VARIABLE') {
      return (
        <Select
          className="flex-1"
          value={props.value?.right}
          onChange={(right) => {
            updateValue({ right });
          }}
          mode={isTargetValueSelectMultiple ? 'multiple' : undefined}
          options={rightOptions}
          placeholder="请选择变量值"
        />
      );
    } else if (rightType === 'CONSTANT') {
      return constantInput;
    } else if (rightType === 'EXPRESSION') {
      return (
        <Expression
          className="flex-1"
          value={props.value?.right}
          onChange={(right) => {
            updateValue({ right });
          }}
          placeholder="编辑表达式"
        />
      );
    }
    return null;
  };

  return (
    <ConfigProvider componentSize={props.fieldSize || 'middle'}>
      <div className={classNames('flex gap-12', props.className)}>
        <Select
          className="flex-1"
          placeholder="请选择变量"
          value={props.value?.left}
          onChange={(left) => {
            const targetValue = rightOptions?.find((item) => item.value === left);
            if (props.fieldMode === 'assignment') {
              if (!targetValue?.varType) {
                console.warn('赋值模式下缺少varType字段');
                return;
              }
              updateValue({ left, right: '', rightFieldType: targetValue.varType });
            } else {
              updateValue({ left, right: '' });
            }
          }}
          options={leftOptions || []}
        />
        {/* > = >= <= */}
        {props.fieldMode !== 'assignment' && (
          <OperatorSelector
            className="flex-1"
            value={props.value?.operator}
            onChange={(operator) => {
              updateValue({ operator });
            }}
          />
        )}
        {/* CONSTANT, VARIABLE, EXPRESSION */}
        <Select
          className="flex-1"
          placeholder="请选择值类型"
          value={rightType}
          onChange={(rightType) => {
            updateValue({ rightType, right: '' });
          }}
          options={calcTypeOptions}
        />

        {renderRightContent()}
      </div>
    </ConfigProvider>
  );
});
